package com.ruoyi.asset.lamp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.asset.common.scopecode.constant.ServiceCode;
import com.ruoyi.asset.common.scopecode.service.IScopeCodeService;
import com.ruoyi.asset.homepage.constant.CommunityConstant;
import com.ruoyi.asset.homepage.constant.ServiceTypeConstant;
import com.ruoyi.asset.lamp.constant.LampDirtConstant;
import com.ruoyi.asset.lamp.domain.LampMaintenance;
import com.ruoyi.asset.lamp.domain.bo.*;
import com.ruoyi.asset.lamp.domain.vo.LampMaintenanceVo;
import com.ruoyi.asset.lamp.mapper.LampMaintenanceMapper;
import com.ruoyi.asset.lamp.service.ILampMaintenanceService;
import com.ruoyi.asset.tool.domain.bo.ToolStatisticsBo;
import com.ruoyi.asset.tool.service.IToolService;
import com.ruoyi.asset.workman.service.IWorkmanService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.tools.excel.MyExcelUtil;
import com.ruoyi.common.tools.excel.base.MyExcelResult;
import com.ruoyi.common.tools.excel.listener.asset.LampMaintenanceExcelListener;
import com.ruoyi.common.tools.utils.SerialGenerator;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.erecord.region.service.IRegionService;
import com.ruoyi.standingbook.lamp.service.ILampService;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author 12276
 */
@RequiredArgsConstructor
@Service
public class LampMaintenanceServiceImpl implements ILampMaintenanceService {

    private final LampMaintenanceMapper lampMaintenanceMapper;
    private final ILampService lampService;
    private IToolService toolService = SpringUtils.getBean(IToolService.class);
    private IRegionService regionService = SpringUtils.getBean(IRegionService.class);
    private IWorkmanService workmanService = SpringUtils.getBean(IWorkmanService.class);
    private ISysDictDataService sysDictDataService = SpringUtils.getBean(ISysDictDataService.class);

    private final IScopeCodeService scopeCodeService;

    private Boolean batchInsertOrUpdate(List<LampMaintenance> voList) {
        return this.lampMaintenanceMapper.insertOrUpdateBatch(voList);
    }

    @Override
    public List<String> importExcel(String excelUrl) {
        List<String> errorMsgList = new ArrayList<>();

        // 生成批次号
        final String batchNo = SerialGenerator.generator.nextId();

        // excel 处理
        MyExcelResult<LampMaintenanceVo> excelResult = MyExcelUtil.getImportExcelData(batchNo, excelUrl,
            new LampMaintenanceExcelListener(batchNo), LampMaintenanceVo.class, true);

        if (null == excelResult) {
            errorMsgList.add("未获取到要处理的数据");

            return null;
        }

        /**
         *  有解析失败就直接返回错误信息
         */
        if(!excelResult.getErrorList().isEmpty()) {
            return excelResult.getErrorList();
        }

        if (!excelResult.getList().isEmpty()) {
            List<LampMaintenance> list = new ArrayList<>();
            AtomicInteger row = new AtomicInteger(0);
            excelResult.getList().forEach(e -> {
                int currentRow = row.incrementAndGet();
                if (e.getDataCheckResult().isSucess()) {
                    LampMaintenance lampMaintenance = new LampMaintenance();
                    BeanCopyUtils.copy(e, lampMaintenance);

                    LampMaintenance oldLampMaintenance = getVoByCondition(lampMaintenance.getLampName(),
                        lampMaintenance.getLampType(), lampMaintenance.getLampAttr());

                    if (oldLampMaintenance != null) {
                        lampMaintenance.setId(oldLampMaintenance.getId());
                    } else {
                        String scopeCode = null;

                        try {
                            scopeCode = scopeCodeService.getNextScopeCode(ServiceCode.LAMP,
                                lampMaintenance.getLampType(), "");
                        } catch (Exception ex) {
                            errorMsgList.add("获取管理范围编码失败，失败原因：" + ex.getMessage());
                        }

                        lampMaintenance.setLampCode(scopeCode);
                    }

                    /**
                     *  如果各行数据校验通过，再遍历检查是否数据重复
                     */
                    if(excelResult.getValidateList().isEmpty()) {
                        AtomicInteger count = new AtomicInteger(0);
                        list.stream().anyMatch(f -> {
                            int currentCount = count.incrementAndGet();
                            if (f.getLampName().equals(lampMaintenance.getLampName()) && f.getLampType().equals(lampMaintenance.getLampType())&& f.getLampAttr().equals(lampMaintenance.getLampAttr())) {
                                errorMsgList.add(String.format("第%d行数据检查失败，失败原因：与第%s行数据重复", currentRow, currentCount));
                                return true;
                            }
                            return false;
                        });
                    }

                    list.add(lampMaintenance);
                } else {
                    errorMsgList.add(String.format("第 %d 行数据检查失败，失败原因：%s",currentRow, e.getDataCheckResult().getMsg()));
                }
            });

            if (errorMsgList.isEmpty()) {
                batchInsertOrUpdate(list);
            }
        }

        return errorMsgList;
    }



    private LampMaintenance getVoByCondition(String lampName, String lampType, String lampAttr) {
        LambdaQueryWrapper<LampMaintenance> lqw = Wrappers.lambdaQuery();

        lqw.eq(LampMaintenance::getLampName, lampName);
        lqw.eq(LampMaintenance::getLampType, lampType);
        lqw.eq(LampMaintenance::getLampAttr, lampAttr);
        lqw.eq(LampMaintenance::getDelFlag,0);

        List<LampMaintenance> list = lampMaintenanceMapper.selectList(lqw);

        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public int deleteLampMaintenance(Set<Long> idsSet) {
        if (CollectionUtils.isEmpty(idsSet)) {
            return -1;
        }
        return lampMaintenanceMapper.logicDeleteLampMaintenance(idsSet);
    }

    @Override
    public TableDataInfo<LampMaintenanceVo> queryLampMaintenance(LampMaintenanceBo searchBo, PageQuery pageQuery) {
        Page<LampMaintenanceVo> result = lampMaintenanceMapper.selectLampMaintenancePage(pageQuery.build(), searchBo);
        ArrayList<LampMaintenanceVo> list = new ArrayList<>();
        result.getRecords().forEach(e -> {
            LampMaintenanceVo lampMaintenanceVo = new LampMaintenanceVo();
            BeanCopyUtils.copy(e, lampMaintenanceVo);
            String lampType = sysDictDataService.selectDictLabel(LampDirtConstant.LAMP_TYPE, lampMaintenanceVo.getLampType());
            if (StringUtils.isNotBlank(lampType)){
                lampMaintenanceVo.setLampType(lampType);
            }
            String lampAttr = sysDictDataService.selectDictLabel(LampDirtConstant.LAMP_ATTR, lampMaintenanceVo.getLampAttr());
            if (StringUtils.isNotBlank(lampAttr)){
                lampMaintenanceVo.setLampAttr(lampAttr);
            }
            list.add(lampMaintenanceVo);

        });
        result.setRecords(list);
        return TableDataInfo.build(result);
    }

    @Override
    public List<LampMaintenanceVo> queryLampMaintenance(LampMaintenanceBo searchBo) {
        ArrayList<LampMaintenanceVo> list = new ArrayList<>();
        lampMaintenanceMapper.exportLampMaintenance(searchBo).forEach(e -> {
            LampMaintenanceVo lampMaintenanceVo = new LampMaintenanceVo();
            BeanCopyUtils.copy(e, lampMaintenanceVo);
            String lampType = sysDictDataService.selectDictLabel(LampDirtConstant.LAMP_TYPE, lampMaintenanceVo.getLampType());
            if (StringUtils.isNotBlank(lampType)){
                lampMaintenanceVo.setLampType(lampType);
            }
            String lampAttr = sysDictDataService.selectDictLabel(LampDirtConstant.LAMP_ATTR, lampMaintenanceVo.getLampAttr());
            if (StringUtils.isNotBlank(lampAttr)){
                lampMaintenanceVo.setLampAttr(lampAttr);
            }
            list.add(lampMaintenanceVo);
        });
        return list;
    }

    @Override
    public LampMaintenanceStatisticsBo getLampCount() {
        LampMaintenanceStatisticsBo statisticsBo = new LampMaintenanceStatisticsBo();
        Integer lampCount = lampMaintenanceMapper.selectLampCount();
        statisticsBo.setLampCount(lampCount);
        int workCount = workmanService.getByServiceType(ServiceTypeConstant.LAMP);
        statisticsBo.setWorkerCount(workCount);
        ToolStatisticsBo toolStatisticsBo = toolService.getCountByServiceType(ServiceTypeConstant.LAMP);
        if (null != toolStatisticsBo) {
            statisticsBo.setEquipmentCount(toolStatisticsBo.getToolCount());
            statisticsBo.setVehicleCount(toolStatisticsBo.getVehicleCount());
        } else {
            statisticsBo.setEquipmentCount(0);
            statisticsBo.setVehicleCount(0);
        }
        return statisticsBo;
    }

    @Override
    public Map getLampCommunityCount() {
        HashMap<String, LampCommunityBo> map = new HashMap<>();
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(CommunityConstant.COMMUNITY_TYPE);
        List<SysDictData> data = sysDictDataService.selectDictDataList(sysDictData);
        for (SysDictData community : data) {
            String communityNo = regionService.getRegionIdByName(community.getDictLabel());
            List<LampTypeBo> lampTypeBos = lampMaintenanceMapper.selectLampCommunityCount(communityNo);
            lampTypeBos.forEach(e->{
                String lampTypeName = sysDictDataService.selectDictLabel(LampDirtConstant.LAMP_TYPE, e.getLampType());
                if (StringUtils.isNotBlank(lampTypeName)){
                    e.setLampType(lampTypeName);
                }
            });
            LampCommunityBo lampCommunityBo = new LampCommunityBo();
            lampCommunityBo.setLampTypeBoList(lampTypeBos);
            ToolStatisticsBo toolCount = toolService.getCountByServiceTypeAndCommunity(ServiceTypeConstant.LAMP, communityNo);
            lampCommunityBo.setToolCount(toolCount.getToolCount());
            lampCommunityBo.setVehicleCount(toolCount.getVehicleCount());
            int workmanCount = workmanService.getCommunityByServiceType(ServiceTypeConstant.LAMP, communityNo);
            lampCommunityBo.setWorkmanCommunity(workmanCount);
            map.put(community.getDictLabel(), lampCommunityBo);
        }
        return map;
    }

    @Override
    public List<LampCommunityCountBo> getLampCountByCommunity(String date) {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(CommunityConstant.COMMUNITY_TYPE);
        List<SysDictData> communities = sysDictDataService.selectDictDataList(sysDictData);
        ArrayList<LampCommunityCountBo> lampCommunityCountBos = new ArrayList<>();
        communities.forEach(e->{
            LampCommunityCountBo lampCommunityCountBo = new LampCommunityCountBo();
            lampCommunityCountBo.setCommunity(e.getDictLabel());
            String regionId = regionService.getRegionIdByName(e.getDictLabel());
            Integer lampNumSum = lampMaintenanceMapper.selectLampCountByCommunity(date, regionId);
            lampCommunityCountBo.setLampCount(lampNumSum);
            ToolStatisticsBo toolCount = toolService.getCommunityByServiceTypeAndDate(ServiceTypeConstant.LAMP, regionId,date);
            if (null != toolCount) {
                lampCommunityCountBo.setEquipmentCount(toolCount.getToolCount());
                lampCommunityCountBo.setVehicleCount(toolCount.getVehicleCount());
            } else {
                lampCommunityCountBo.setEquipmentCount(0);
                lampCommunityCountBo.setVehicleCount(0);
            }
            int workmanCount = workmanService.getCommunityByServiceTypeAndDate(ServiceTypeConstant.LAMP, regionId,date);
            lampCommunityCountBo.setWorkerCount(workmanCount);
            lampCommunityCountBos.add(lampCommunityCountBo);
        });
        return lampCommunityCountBos;
    }

    @Override
    public Integer getLampCountByDateAndCommunity(String date, String community) {
        Integer lampNumSum;
        if (StringUtils.isNotEmpty(community)) {
            String regionId = regionService.getRegionIdByName(community);
            lampNumSum = lampMaintenanceMapper.selectLampCountByCommunity(date, regionId);
        } else {
            lampNumSum = lampMaintenanceMapper.selectLampCountByCommunity(date, null);
        }
        if (null == lampNumSum) lampNumSum=0;
        return lampNumSum;
    }

    @Override
    public LampWorkStatisticsBo getLampWorkByDate(String date) {
        LampWorkStatisticsBo lampWorkStatisticsBo = new LampWorkStatisticsBo();
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(CommunityConstant.COMMUNITY_TYPE);
        List<SysDictData> communities = sysDictDataService.selectDictDataList(sysDictData);
        ArrayList<Integer> lampNumList = new ArrayList<>();
        communities.forEach(e->{
            String regionId = regionService.getRegionIdByName(e.getDictLabel());
            Integer lampNumSum = lampMaintenanceMapper.selectLampCountByCommunity(date, regionId);
            lampNumList.add(lampNumSum);
        });
        int total = lampNumList.stream().reduce(Integer::sum).orElse(0);
        lampWorkStatisticsBo.setTotal(total);
        Integer finishedSum = lampService.getSumByDate(date);
        if (finishedSum == null) {
            finishedSum = 0;
        }
        lampWorkStatisticsBo.setFinishedSum(finishedSum);
        if (finishedSum == 0 || total == 0){
            lampWorkStatisticsBo.setPercent(BigDecimal.ZERO);
        } else {
            BigDecimal pec = BigDecimal.valueOf(finishedSum).divide(BigDecimal.valueOf(total),2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
            pec = pec.compareTo(BigDecimal.valueOf(100)) > 0 ? BigDecimal.valueOf(100) : pec;
            lampWorkStatisticsBo.setPercent(pec);
        }
        return lampWorkStatisticsBo;
    }

    @Override
    public LampWorkStatisticsBo getLampWorkByDateAndCommunity(String date, String community) {
        LampWorkStatisticsBo lampWorkStatisticsBo = new LampWorkStatisticsBo();
        String regionId = regionService.getRegionIdByName(community);
        Integer lampNumSum = lampMaintenanceMapper.selectLampCountByCommunity(date, regionId);
        if(lampNumSum == null) {
            lampNumSum = 0;
        }
        lampWorkStatisticsBo.setTotal(lampNumSum);
        Integer finishedSum = lampService.getSumByDateAndCommunity(date,community);
        if(finishedSum == null) {
            finishedSum = 0;
        }
        lampWorkStatisticsBo.setFinishedSum(finishedSum);
        if (finishedSum == 0 || lampNumSum == 0){
            lampWorkStatisticsBo.setPercent(BigDecimal.ZERO);
        } else {
            BigDecimal pec = BigDecimal.valueOf(finishedSum).divide(BigDecimal.valueOf(lampNumSum),2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
            pec = pec.compareTo(BigDecimal.valueOf(100)) > 0 ? BigDecimal.valueOf(100) : pec;
            lampWorkStatisticsBo.setPercent(pec);
        }
        return lampWorkStatisticsBo;
    }

    @Override
    public LampCommunityMapBo getCommunityByDate(String community, String date) {
        HashMap<String, String> map = new HashMap<>(32);
        String communityNo = regionService.getRegionIdByName(community);
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(LampDirtConstant.LAMP_TYPE);
        List<SysDictData> data = sysDictDataService.selectDictDataList(sysDictData);
        List<LampTypeBo> lampTypeBos = lampMaintenanceMapper.selectLampCommunityCount(communityNo);
        buildLampTypeMap(data,lampTypeBos,map);
        LampCommunityMapBo lampCommunityMapBo = new LampCommunityMapBo();
        lampCommunityMapBo.setLampTypeMap(map);
        ToolStatisticsBo toolCount = toolService.getCountByServiceTypeAndCommunity(ServiceTypeConstant.LAMP, communityNo);
        lampCommunityMapBo.setToolCount(toolCount.getToolCount());
        lampCommunityMapBo.setVehicleCount(toolCount.getVehicleCount());
        int workmanCount = workmanService.getCommunityByServiceType(ServiceTypeConstant.LAMP, communityNo);
        lampCommunityMapBo.setWorkmanCommunity(workmanCount);
        return lampCommunityMapBo;
    }

    /**
     * 组装数据
     * @param data
     * @param lampTypeBos
     * @param map
     */
    private void buildLampTypeMap(List<SysDictData> data,List<LampTypeBo> lampTypeBos,HashMap<String, String> map){
        ArrayList<String> typeName = new ArrayList<>();
        for (SysDictData lampType : data) {
            if (lampTypeBos.size() > 0) {
                for (LampTypeBo lampTypeBo : lampTypeBos) {
                    if (lampType.getDictValue().equals(lampTypeBo.getLampType())) {
                        typeName.add(lampType.getDictLabel());
                        map.put(lampType.getDictLabel(),lampTypeBo.getLampCount());
                    }
                }
            } else {
                map.put(lampType.getDictLabel(),"0");
            }
        }
        if (typeName.size() > 0) {
            List<String> labelList = data.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
            labelList.removeAll(typeName);
            labelList.forEach(e->{
                map.put(e,"0");
            });
        }
    }

}
